import { Form, Input, Select, message, Image, Tree, Upload } from 'myselfantd'
import React, { useState, useEffect, memo, useMemo, useCallback } from 'react'
import { useRequest } from 'myselfantd/hooks'
import styles from './index.module.scss'
// import {
//   findPortalAlls,
//   addConsumerCompany,
//   findConsumerCompanyDetail,
//   updateConsumerCompany
// } from '../api'
import { AESencode } from '@/utils/common'
type viewmode = 'view' | 'add' | 'edit'
interface AddFormProps {
  close: Function
  onFinish: Function
  viewmode: viewmode
  params?: any
}
const App: React.FC<AddFormProps> = memo(
  ({ close, onFinish, viewmode, params }) => {
    const [formData, setFormData] = useState({} as any)
    // const [treeData] = useRequest({
    //   request: findPortalAlls,
    //   transform: ({ result }) => result
    // })
    const treeData=[]
    let expandTreeData: any = []
    const transformTree = (arr: any) => {
      arr.forEach((item: any) => {
        expandTreeData.push({
          ...item,
          subMenus: item.subMenus?.length ? 1 : 0
        })
        if (item.subMenus?.length) {
          transformTree(item.subMenus)
        }
      })
    }
    useEffect(() => {
      if (treeData?.length && viewmode !== 'add') {
        getFormData()
      }
    }, [treeData])
    const getFormData = async () => {
      // let { result } = await findConsumerCompanyDetail(params.id)
      // const getFlat = (data: any, target: any) => {
      //   for (let i = 0; i < data.length; i++) {
      //     let { subMenus, ...rest } = data[i]
      //     target.push(rest)
      //     if (subMenus) {
      //       getFlat(subMenus, target)
      //     }
      //   }
      //   return target
      // }
      // transformTree(treeData)
      // result.menuList = result.checkedMenuIds.filter(
      //   (item: any) =>
      //     expandTreeData.find((item1: any) => item1.id === item)?.subMenus === 0
      // )
      // setFormData({ ...result })
    }
    return (
      <div className={styles.addContent}>
        <Form.Layout
          viewmode={viewmode}
          title={'基础信息'}
          data={formData}
          request={async (val: any) => {
            const filterFunc = (root: any) => {
              if (Array.isArray(root.subMenus)) {
                root.subMenus = root.subMenus.filter(filterFunc)
              }
              return val.menuList.includes(root.id) || root.subMenus?.length
            }
            val.menuList = treeData?.filter(filterFunc)
            // if (viewmode === 'add') {
            //   const password = AESencode(val.password)
            //   let res = await addConsumerCompany({ ...val, password })
            //   if (res.message === 'success') {
            //     message.success('创建成功')
            //     onFinish()
            //   }
            // } else {
            //   if (!val.password) {
            //     delete val.password
            //   } else {
            //     val.password = AESencode(val.password)
            //   }
            //   let res = await updateConsumerCompany({ ...val, id: params.id })
            //   if (res.message === 'success') {
            //     message.success('修改成功')
            //     onFinish()
            //   }
            // }
          }}
          formItemData={useMemo(
            () =>
              [
                [
                  {
                    name: 'companyName',
                    label: '企业名称',
                    rules: [
                      {
                        required: true,
                        message: '企业名称必填',
                        trigger: 'blur'
                      }
                    ],
                    render: () => <Input placeholder="请输入" />
                  },
                  {
                    name: 'creditCode',
                    label: '企业信用代码',
                    rules: [
                      {
                        required: true,
                        message: '企业信用代码必填',
                        trigger: 'blur'
                      },
                      {
                        min: 18,
                        max: 18,
                        message: '企业信用代码不低于18位数',
                        trigger: 'blur'
                      },
                      {
                        pattern: /^([0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}|[1-9]\d{14})$/,
                        message: '请输入正确的企业信用代码',
                        trigger: 'blur'
                      }
                    ],
                    render: () => (
                      <Input placeholder="请输入" showCount maxLength={18} />
                    ),
                    editRender: () => (
                      <Input
                        disabled
                        placeholder="请输入"
                        showCount
                        maxLength={18}
                      />
                    )
                  }
                ],
                [
                  {
                    name: 'username',
                    label: '企业账号',
                    rules: [
                      {
                        required: true,
                        message: '企业账号必填',
                        trigger: 'blur'
                      },
                      {
                        pattern: /^[a-zA-Z0-9]{3,11}$/,
                        message: '账号只能为字母数字，长度范围3~11'
                      }
                    ],
                    render: () => (
                      <Input
                        autoComplete="new-password"
                        placeholder="请输入"
                        showCount
                        minLength={3}
                        maxLength={11}
                      />
                    ),
                    editRender: () => (
                      <Input
                        disabled
                        placeholder="请输入"
                        showCount
                        minLength={3}
                        maxLength={11}
                      />
                    )
                  },
                  {
                    name: 'password',
                    label: viewmode === 'edit' ? '新密码' : '密码',
                    rules:
                      viewmode === 'add'
                        ? [
                            {
                              required: true,
                              message: '密码必填',
                              trigger: 'blur'
                            },
                            {
                              pattern: /^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[#@!~%^&*]).{6,10}$/,
                              message:
                                '密码必须为6~10位包括大小写字母、数字、特殊字符(#@!~%^&*)！'
                            }
                          ]
                        : viewmode === 'edit'
                        ? [
                            {
                              pattern: /^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[#@!~%^&*]).{6,10}$/,
                              message:
                                '密码必须为6~10位包括大小写字母、数字、特殊字符(#@!~%^&*)！'
                            }
                          ]
                        : [],
                    render: () => (
                      <Input.Password
                        autoComplete="new-password"
                        placeholder="请输入"
                      />
                    ),
                    viewRender: () => '--'
                  }
                ],
                [
                  {
                    name: 'nickname',
                    label: '联系人',
                    rules: [
                      { required: true, message: '联系人必填', trigger: 'blur' }
                    ],
                    render: () => (
                      <Input placeholder="请输入" showCount maxLength={20} />
                    )
                  },
                  {
                    name: 'phone',
                    label: '联系电话',
                    rules: [
                      {
                        required: true,
                        message: '联系电话必填',
                        trigger: 'blur'
                      },
                      {
                        min: 11,
                        message: '手机号码不低于11位数',
                        trigger: 'blur'
                      },
                      {
                        pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
                        message: '请输入正确的手机号码格式'
                      }
                    ],
                    render: () => (
                      <Input placeholder="请输入" showCount maxLength={11} />
                    )
                  }
                ],
                [
                  {
                    name: 'email',
                    label: '联系邮箱',
                    rules: [
                      {
                        required: true,
                        message: '联系邮箱必填',
                        trigger: 'blur'
                      },
                      {
                        pattern: /^[0-9a-zA-Z_]{3,30}@[A-Za-z0-9-]{1,20}(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,6})$/,
                        message: '请输入正确的邮箱格式'
                      }
                    ],
                    render: () => (
                      <Input autoComplete="new-password" placeholder="请输入" />
                    )
                  },
                  {
                    name: 'cooperateType',
                    label: '合作类型',
                    rules: [{ required: true, message: '合作类型必填' }],
                    render: () => (
                      <Select placeholder="请选择" allowClear>
                        <Select.Option value={0}>合同客户</Select.Option>
                        <Select.Option value={1}>临时客户</Select.Option>
                      </Select>
                    ),
                    viewRender: (_: any) => {
                      enum TYPE {
                        合同客户 = 0,
                        临时客户 = 1
                      }
                      return TYPE[_]
                    }
                  }
                ],
                [
                  {
                    name: 'address',
                    label: '联系地址',
                    render: () => <Input placeholder="请输入" />
                  }
                ],
                [
                  {
                    name: 'businessLicenseUrl',
                    label: '企业照片',
                    render: () => (
                      <Upload urlTemplate={`${'UPLOAD_IMG_URL_NEW'}/hxdfs/{0}`} />
                    ),
                    viewRender: () => (
                      <Image.Form
                        urlTemplate={`${'UPLOAD_IMG_URL_NEW'}/hxdfs/{0}`}
                        width={120}
                        height={120}
                      />
                    )
                  }
                ],
                [
                  {
                    name: 'remark',
                    label: '说 明',
                    render: () => <Input.TextArea showCount maxLength={100} />
                  }
                ],
                [
                  {
                    name: 'menuList',
                    viewRender: () => {
                      return (
                        <Tree
                          disabled
                          defaultExpandAll={true}
                          defaultExpandParent={true}
                          title="权限配置"
                          fieldNames={{
                            title: 'name',
                            key: 'id',
                            children: 'subMenus'
                          }}
                          treeData={treeData}
                        />
                      )
                    },
                    render: () => {
                      return (
                        <Tree
                          defaultExpandAll={true}
                          defaultExpandParent={true}
                          title="权限配置"
                          fieldNames={{
                            title: 'name',
                            key: 'id',
                            children: 'subMenus'
                          }}
                          treeData={treeData}
                        />
                      )
                    }
                  }
                ]
              ] as any,
            [treeData]
          )}
          onFinish={close}
        ></Form.Layout>
      </div>
    )
  }
)

export default App
